<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\UserActionsLog;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use Hyperf\Context\Context;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * Note -
 * DateTime 2024/8/2 16:47
 * User Admin
 * Class ApiLogMiddleware
 * @package App\Middleware
 */
class ApiLogMiddleware implements MiddlewareInterface
{
    public RequestInterface $request;

    public function __construct(protected ContainerInterface $container, RequestInterface $request)
    {
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $params = $request->getParsedBody();
        $apiLogId = UserActionsLog::query()->insertGetId([
            'uid' => $params['uid'] ?? 0,
            'imei' => $params['imei'] ?? '',
            'ip' => FunUtil::getClientIp(),
            'actions' => $request->getUri()->getPath(),
            'params' => json_encode($params),
            'ctime' => time(),
        ]);
        Context::set('apiLogId', $apiLogId);
        $response = $handler->handle($request);
        $body = $response->getBody();
        $contents = $body->getContents();
        UserActionsLog::query()->where('id', $apiLogId)->update(['response' => $contents]);
        // return $response;

        // 重新写入返回数据，以便响应客户端
        $responseData = json_decode($contents, true);
        if (isset($responseData['text'])) {
            unset($responseData['text']);
        }
        return $response->withBody(new SwooleStream(json_encode($responseData)));
    }
}
